/**
 * Copyright (c) 2017-2018,Retire 吴益峰 (372310383@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.jplus.core.base;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.ext.interceptor.NotAction;
import com.jfinal.json.FastJson;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.render.JsonRender;
import io.jboot.web.controller.JbootController;
import io.jplus.Consts;
import io.jplus.core.render.AjaxResult;
import org.apache.shiro.authz.annotation.RequiresUser;

import java.util.List;
import java.util.Map;

public class BaseController extends JbootController {

    public static final String BASE_VIEW_PATH = Consts.BASE_VIEW_PATH;

    @RequiresUser
    public void index(){
        render(Consts.LIST_HTML);
    }

    protected int getPageNumber() {
        int page = getParaToInt("page", 1);
        if (page < 1) {
            page = 1;
        }
        return page;
    }

    protected int getPageSize() {
        int size = getParaToInt("size", 10);
        if (size < 1) {
            size = 1;
        }
        return size;
    }

    /**
     * 将前端传递过来的Json转换成对应的Model对象
     *
     * @param t   Model对象类
     * @param <T> 返回对应的Model对象
     * @return
     */
    public <T extends Model> T jsonToModel(Class<T> t) {
        String jsonString = HttpKit.readData(getRequest());
        setAttr("parameters", StrKit.notBlank(jsonString) ? jsonString : "{}");
        T model = null;
        if (StrKit.notBlank(jsonString)) {
            //logger.info("前端参数: {}",jsonString);
            try {
                Map<String, Object> map = FastJson.getJson().parse(jsonString, Map.class);
                model = t.newInstance();
                model.put(map);
                //transformId(model);
                //model.put(ModelCopier.MODEL_FROM_COPIER, true);
                model.put("_auto_copy_model_", true);
            } catch (InstantiationException e) {
                //logger.error(e.getMessage());
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                //logger.error(e.getMessage());
                e.printStackTrace();
            }
        }
        return model;
    }


    @Before(NotAction.class)
    protected void renderAjaxResultForSuccess() {
        renderAjaxResult("success", 0, null);
    }

    @Before(NotAction.class)
    protected void renderAjaxResultForSuccess(String message) {
        renderAjaxResult(message, 0, null);
    }

    @Before(NotAction.class)
    protected void renderAjaxResultForSuccess(String message, Object data) {
        renderAjaxResult(message, 0, data);
    }

    @Before(NotAction.class)
    protected void renderAjaxResultForError() {
        renderAjaxResult("error", 1, null);
    }

    @Before(NotAction.class)
    protected void renderAjaxResultForError(String message) {
        renderAjaxResult(message, 1, null);
    }

    @Before(NotAction.class)
    protected void renderAjaxResult(String message, int errorCode) {
        renderAjaxResult(message, errorCode, null);
    }

    @Before(NotAction.class)
    protected void renderAjaxResult(String message, int errorCode, Object data) {
        AjaxResult ar = new AjaxResult();
        ar.setMessage(message);
        ar.setErrorCode(errorCode);
        ar.setData(data);

        if (isIEBrowser()) {
            render(new JsonRender(ar).forIE());
        } else {
            renderJson(ar);
        }
    }

    @Before(NotAction.class)
    protected void renderPageForBT(Page<?> page){
        JSONObject jo = new JSONObject();
        jo.put("total",page.getTotalRow());
        jo.put("rows",page.getList());
        renderJson(jo);
    }

    @Before(NotAction.class)
    protected void renderListForBT(List<?> list){
        JSONObject jo = new JSONObject();
        jo.put("total",list.size());
        jo.put("rows",list);
    }

}
